import requests
from config.Peizhi import xnqqp
from datetime import datetime

# 从配置文件中获取气瓶配置信息
xnq = xnqqp()
# Django REST framework 的 API 地址，用于推送故障信息
django_api_url = "http://222.134.245.144:17000/weizhang/VioModel/"

# 推送故障信息到 Django REST framework
def send_fault_to_django(fault_info):
    try:
        # 发送 POST 请求，将故障信息以 JSON 格式发送到指定的 Django API 地址
        response = requests.post(django_api_url, json=fault_info)
        if response.status_code == 201:
            # 若请求成功（状态码为 201），打印成功信息并显示响应的 JSON 数据
            print(f"成功推送故障信息到 Django REST framework: {response.json()}")
        else:
            # 若请求失败，打印失败信息，包含状态码和响应内容
            print(f"推送故障信息失败，状态码: {response.status_code}, 响应内容: {response.text}")
    except requests.RequestException as e:
        # 若请求过程中发生异常，打印异常信息
        print(f"请求发生错误: {e}")

# 气瓶处理逻辑的主方法
def Xnq(url, device_name):
    try:
        # 发送 GET 请求到指定的 URL
        response = requests.get(url)
        # 检查请求是否成功
        if response.status_code == 200:
            # 解析响应数据为 JSON 格式
            data = response.json()
            # 获取结果部分
            results = data.get("results", [])
            # 如果没有结果，直接返回空列表
            if not results:
                print(f"API {url} 返回结果为空")
                # 构造故障信息
                fault_info = {
                    "gu_zhang_ming_cheng": "API返回结果为空",
                    "she_bei_ming_cheng": device_name,
                    "she_bei_qu_yu": "气瓶",
                    "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                    "gu_zhang_lei_xing": "数据获取异常",
                    "shi_ji_zhi": 0,
                    "gao_jing_zhi": 0,
                    "gu_zhang_miao_shu": f"API {url} 返回结果为空，设备名称: {device_name}",
                    "chu_li_zhuang_tai": "未处理"
                }
                # 推送故障信息到 Django API
                send_fault_to_django(fault_info)
                return []
            # 取最新的一条数据
            latest_result = results[-1]
            # 获取设备 ID
            device_id = latest_result.get("id")
            # 获取设备数据
            device_data = latest_result.get("data", [])
            # 检查 device_data 是否是列表
            if not isinstance(device_data, list):
                print(f"设备 {device_name} 的数据格式错误，设备ID: {device_id}")
                # 构造故障信息
                fault_info = {
                    "gu_zhang_ming_cheng": "设备数据格式错误",
                    "she_bei_ming_cheng": device_name,
                    "she_bei_qu_yu": "气瓶",
                    "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                    "gu_zhang_lei_xing": "数据异常",
                    "shi_ji_zhi": 0,
                    "gao_jing_zhi": 0,
                    "gu_zhang_miao_shu": f"设备 {device_name} 的数据格式错误，设备ID: {device_id}",
                    "chu_li_zhuang_tai": "未处理"
                }
                # 推送故障信息到 Django API
                send_fault_to_django(fault_info)
                return []
            # 输出设备的 ID 和数据
            print(f"设备 {device_name}的ID:{device_id}")
            print(f"设备 {device_name} 的数据: {', '.join(map(str, device_data))}")
            # 检查数据是否足够（每个设备有 20 个温度值）
            if len(device_data) < 20:
                print(f"设备 {device_name}的ID:{device_id} 热成像传感器损坏")
                # 构造故障信息
                fault_info = {
                    "gu_zhang_ming_cheng": "热成像传感器损坏",
                    "she_bei_ming_cheng": device_name,
                    "she_bei_qu_yu": "气瓶",
                    "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                    "gu_zhang_lei_xing": "设备故障",
                    "shi_ji_zhi": 0,
                    "gao_jing_zhi": 0,
                    "gu_zhang_miao_shu": f"设备 {device_name}的ID:{device_id} 热成像传感器损坏",
                    "chu_li_zhuang_tai": "未处理"
                }
                # 推送故障信息到 Django API
                send_fault_to_django(fault_info)
                return []
            # 将前 10 个温度值作为等高点温度，后 10 个温度值作为等中点温度
            high_points = device_data[:10]  # 前 10 个值为等高点温度
            mid_points = device_data[10:20]  # 后 10 个值为等中点温度

            # 计算等高点和等中点温度的平均值
            high_avg = sum(high_points) / len(high_points)
            mid_avg = sum(mid_points) / len(mid_points)
            # 从配置信息中获取高位和中位的容差范围
            gaowei = xnq.gaowei
            zhongwei = xnq.zhongwei
            # 设置一个开关，全部正常就输出正常
            all_normal = True
            # 遍历检查每个气瓶的温度
            for i in range(10):
                high_temp = high_points[i]
                mid_temp = mid_points[i]
                gao = high_temp - high_avg
                zhong = mid_temp - mid_avg
                if gao > gaowei or gao < -gaowei:
                    print(f"{device_name}的ID:{device_id} 等高点温度平均值异常，当前值: {high_temp},正常范围（+-{gaowei}）")
                    # 构造故障信息
                    fault_info = {
                        "gu_zhang_ming_cheng": "等高点温度平均值异常",
                        "she_bei_ming_cheng": device_name,
                        "she_bei_qu_yu": "气瓶",
                        "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                        "gu_zhang_lei_xing": "温度异常",
                        "shi_ji_zhi": high_temp,
                        "gao_jing_zhi": high_avg + gaowei,
                        "gu_zhang_miao_shu": f"{device_name}的ID:{device_id} 等高点温度平均值异常，当前值: {high_temp},正常范围（+-{gaowei}）",
                        "chu_li_zhuang_tai": "未处理"
                    }
                    # 推送故障信息到 Django API
                    send_fault_to_django(fault_info)
                    all_normal = False
                elif zhong > zhongwei or zhong < -zhongwei:
                    print(f"设备 {device_name}的ID:{device_id} 等中点温度平均值异常，当前值: {mid_temp},正常范围（+-{zhongwei}）")
                    # 构造故障信息
                    fault_info = {
                        "gu_zhang_ming_cheng": "等中点温度平均值异常",
                        "she_bei_ming_cheng": device_name,
                        "she_bei_qu_yu": "气瓶",
                        "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                        "gu_zhang_lei_xing": "温度异常",
                        "shi_ji_zhi": mid_temp,
                        "gao_jing_zhi": mid_avg + zhongwei,
                        "gu_zhang_miao_shu": f"设备 {device_name}的ID:{device_id} 等中点温度平均值异常，当前值: {mid_temp},正常范围（+-{zhongwei}）",
                        "chu_li_zhuang_tai": "未处理"
                    }
                    # 推送故障信息到 Django API
                    send_fault_to_django(fault_info)
                    all_normal = False
            if all_normal:
                print(f"设备 {device_name}的ID:{device_id} 所有气瓶检查完成！正常")
            return [latest_result]
        else:
            print(f"请求失败，状态码: {response.status_code}")
            # 构造故障信息
            fault_info = {
                "gu_zhang_ming_cheng": "请求失败",
                "she_bei_ming_cheng": device_name,
                "she_bei_qu_yu": "气瓶",
                "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                "gu_zhang_lei_xing": "请求异常",
                "shi_ji_zhi": response.status_code,
                "gao_jing_zhi": 200,
                "gu_zhang_miao_shu": f"请求 {url} 失败，状态码: {response.status_code}，设备名称: {device_name}",
                "chu_li_zhuang_tai": "未处理"
            }
            # 推送故障信息到 Django API
            send_fault_to_django(fault_info)
            return []
    except requests.RequestException as e:
        print(f"请求发生错误: {e}")
        # 构造故障信息
        fault_info = {
            "gu_zhang_ming_cheng": "请求发生错误",
            "she_bei_ming_cheng": device_name,
            "she_bei_qu_yu": "气瓶",
            "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
            "gu_zhang_lei_xing": "请求异常",
            "shi_ji_zhi": 0,
            "gao_jing_zhi": 0,
            "gu_zhang_miao_shu": f"请求 {url} 发生错误: {e}，设备名称: {device_name}",
            "chu_li_zhuang_tai": "未处理"
        }
        # 推送故障信息到 Django API
        send_fault_to_django(fault_info)
        return []

# 蓄能器安全阀 1 检查函数
def XnqX1():
    # 模拟从超声流量计获取流量数据
    url = "http://222.134.245.144:17000/chuanganqi/Csxnq01DeviceModel/"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        results = data.get("results", [])
        latest_result = results[-1]
        xnqid = latest_result.get("id")
        xnqdata = latest_result.get("data")
        if xnqdata != 0:
            print(f"蓄能器 1 阀门泄露 瞬时流量为:{xnqdata}")
            # 构造故障信息
            fault_info = {
                "gu_zhang_ming_cheng": "蓄能器阀门泄露",
                "she_bei_ming_cheng": "蓄能器 1",
                "she_bei_qu_yu": "蓄能器",
                "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                "gu_zhang_lei_xing": "流量异常",
                "shi_ji_zhi": xnqdata,
                "gao_jing_zhi": 0,
                "gu_zhang_miao_shu": f"蓄能器 1 阀门泄露 瞬时流量为:{xnqdata}",
                "chu_li_zhuang_tai": "未处理"
            }
            # 推送故障信息到 Django API
            send_fault_to_django(fault_info)
        else:
            print("蓄能器 1 阀门泄露未发现泄露")

# 蓄能器安全阀 2 检查函数
def XnqX2():
    # 模拟从超声流量计获取流量数据
    url = "http://222.134.245.144:17000/chuanganqi/Csxnq02DeviceModel/"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        results = data.get("results", [])
        latest_result = results[-1]
        xnqid = latest_result.get("id")
        xnqdata = latest_result.get("data")
        if xnqdata != 0:
            print(f"蓄能器 2 阀门泄露 瞬时流量为:{xnqdata}")
            # 构造故障信息
            fault_info = {
                "gu_zhang_ming_cheng": "蓄能器阀门泄露",
                "she_bei_ming_cheng": "蓄能器 2",
                "she_bei_qu_yu": "蓄能器",
                "gu_zhang_shi_jian": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
                "gu_zhang_lei_xing": "流量异常",
                "shi_ji_zhi": xnqdata,
                "gao_jing_zhi": 0,
                "gu_zhang_miao_shu": f"蓄能器 2 阀门泄露 瞬时流量为:{xnqdata}",
                "chu_li_zhuang_tai": "未处理"
            }
            # 推送故障信息到 Django API
            send_fault_to_django(fault_info)
        else:
            print("蓄能器 2 阀门泄露未发现泄露")

# 1 号气瓶检查函数
def Qip1():
    url1 = "http://222.134.245.144:17000/chuanganqi/Rcx01DeviceModel/"
    url2 = "http://222.134.245.144:17000/chuanganqi/Rcx02DeviceModel/"
    # 检查 1 号 1 - 10 设备
    Xnq(url1, "1 号 1 - 10 设备")
    # 检查 1 号 11 - 20 设备
    Xnq(url2, "1 号 11 - 20 设备")
    print(f"1 号设备检查完成")

# 2 号气瓶检查函数
def Qip2():
    url1 = "http://222.134.245.144:17000/chuanganqi/Rcx03DeviceModel/"
    url2 = "http://222.134.245.144:17000/chuanganqi/Rcx04DeviceModel/"
    # 检查 2 号 1 - 10 设备
    Xnq(url1, "2 号 1 - 10 设备")
    # 检查 2 号 11 - 20 设备
    Xnq(url2, "2 号 11 - 20 设备")
    print(f"2 号设备检查完成")

# 依次执行蓄能器和气瓶的检查函数
XnqX1()
XnqX2()
Qip1()
Qip2()